package com.linewell.utils;

import com.google.gson.Gson;
import com.linewell.entity.Focus;
import com.linewell.entity.Message;
import com.linewell.entity.UserInfo;
import com.linewell.service.IFocusService;
import com.linewell.service.IMessageService;
import org.springframework.web.context.ContextLoader;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@ServerEndpoint(value="/chat",configurator=HttpSessionConfigurator.class)
public class ChatSocket {

	private static IFocusService focusService = (IFocusService) ContextLoader.getCurrentWebApplicationContext().getBean("focusService");
	private static IMessageService messageService = (IMessageService) ContextLoader.getCurrentWebApplicationContext().getBean("messageService");
	private static Gson gson=new Gson();
	private static Map<Long,Session> chatUser=new HashMap<Long,Session>();
	private List<Long> userList;
	private UserInfo LoginUser;

	public ChatSocket(){
		userList=new ArrayList<Long>();
	}
	
	@OnOpen
	public void open(Session session,EndpointConfig config){
		//获取HttpSession
		HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        System.out.println(httpSession.getAttribute("LoginUser"));
		LoginUser = (UserInfo) httpSession.getAttribute("LoginUser");
		//将在线用户添加到chatUser中
		chatUser.put(LoginUser.getUserId(),session);
		//获得用户的关注人的id集合
		Focus focus = focusService.selectAllFocus(LoginUser.getUserId());
		//登录用户关注的人
		List<UserInfo> userInfoList1 = focus.getUserInfoList();
		for (UserInfo userInfo : userInfoList1) {
			userList.add(userInfo.getUserId());
		}
	}
	
	@OnMessage
	public void message(Session session,String data){
		System.out.println(data);
		Message message=gson.fromJson(data, Message.class);

		//1发消息  2上线  3下线  4回馈  5初始化  6输入提示
		if(message.getType()==1){
			if(chatUser.containsKey(message.getReceiver().getUserId())){
				message.setIsRead(1);
				try {
					chatUser.get(message.getReceiver().getUserId()).getBasicRemote().sendText(gson.toJson(message));
					message.setType(4);
					session.getBasicRemote().sendText(gson.toJson(message));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				message.setSender(LoginUser);
				//messageService.InsertMessage(message);
			}
		}

		if(message.getType()==2){
			//验证对方是否在线
			Message reMessage=new Message();
			reMessage.setType(2);
			System.out.println(message.getReceiver().getUserId());
			System.out.println(chatUser.containsKey(message.getReceiver().getUserId()));
			if(chatUser.containsKey(message.getReceiver().getUserId())){
				reMessage.setContent("在线");
			}else{
				reMessage.setContent("对方不在线");
			}
			try {
				session.getBasicRemote().sendText(gson.toJson(reMessage));
			} catch (IOException e) {
				e.printStackTrace();
			}

			//上线提醒其他人
			for (Long userId : userList) {
				if(chatUser.containsKey(userId)){
					try {
						if(!chatUser.get(userId).isOpen()){
							chatUser.remove(session);
							System.out.println("0.0");
							continue;
						}
						chatUser.get(userId).getBasicRemote().sendText(gson.toJson(new Message("在线",2)));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		if(message.getType()==3){

			//下线提醒其他人
			for (Long userId : userList) {
				if(chatUser.containsKey(userId)){
					try {
						if(!chatUser.get(userId).isOpen()){
							chatUser.remove(session);
							continue;
						}
						chatUser.get(userId).getBasicRemote().sendText(gson.toJson(new Message("对方不在线",2)));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			//移除用户
			Collection<Session> sessionTemp =chatUser.values();
			sessionTemp.remove(session);
//			for (Entry<Long, Session> entry : chatUser.entrySet()) {
//				System.out.println("0.0"+entry.getKey()+" "+entry.getValue());
//			}
			try {
				session.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//回馈
		if(message.getType()==4){
			if(chatUser.containsKey(message.getReceiver().getUserId())){
				try {
					chatUser.get(message.getReceiver().getUserId()).getBasicRemote().sendText(gson.toJson(message));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			//改变消息状态   初始化未读数据及未接收数据
			if(message.getUnreceivedMessage()!=null) {
				List<Long> messages=new ArrayList<Long>();
				for (Message messageTemp : message.getUnreceivedMessage()) {
					messages.add(messageTemp.getMessageId());
				}
				if(messages.size()>0){
					//messageService.updateBatchState(messages);
				}
			}
		}

		//初始化
		if(message.getType()==5){
			message.setSender(LoginUser);
			//List<Message> messageList=messageService.getMessageList(message.getSender().getUserId(), message.getReceiver().getUserId());
			//message.setUnreadMessage(messageList);
			//messageList=messageService.getMessageList(message.getReceiver().getUserId(), message.getSender().getUserId());
			//message.setUnreceivedMessage(messageList);
			message.setType(5);
			try {
				session.getBasicRemote().sendText(gson.toJson(message));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//输入提示
		if(message.getType()==6){
			if(chatUser.containsKey(message.getReceiver().getUserId())){
				try {
					UserInfo userInfo=new UserInfo();
					userInfo.setUserId(this.LoginUser.getUserId());
					message.setSender(userInfo);
					chatUser.get(message.getReceiver().getUserId()).getBasicRemote().sendText(gson.toJson(message));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	@OnClose
	public void close(Session session){
		//删除没有在线的用户
		chatUser.remove(session);
	}
	

}
